package com.wswy.wzcx.ui.module.lbs

import android.arch.lifecycle.LiveData
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiSearch
import com.wswy.wzcx.AppContext
import com.wswy.wzcx.module.base.BaseViewModel
import com.wswy.wzcx.module.base.SingleLiveData
import timber.log.Timber

class LbsViewModel : BaseViewModel(), PoiSearch.OnPoiSearchListener {
    private companion object {
        private const val PAGE_SIZE = 50
    }


    private var currentPage = 0

    private var pendingPage = 1
    private var maxPage = 1
    private var isLoading = false

    private val gasListLiveData = SingleLiveData<List<PoiItem>?>()

    var point:LatLonPoint?=null

    var code :String?= null

    fun reset(){
        currentPage = 0
        pendingPage = 1
        maxPage =1
    }

    fun loadNearby(page:Int = 1,loadPageSize : Int = PAGE_SIZE){

        point?:return
        code?:return

        if (isLoading){
            return
        }
        isLoading = true

        Timber.e("load --> $code  page:$page  point:$point")

        val query = PoiSearch.Query(null, code).apply {

            pageSize = loadPageSize
            pageNum = page
        }


        val poiSearch = PoiSearch(AppContext.getContext(), query)

        poiSearch.bound = PoiSearch.SearchBound(point, 1000*5)

        poiSearch.setOnPoiSearchListener(this)

        poiSearch.searchPOIAsyn()
    }


    override fun onPoiItemSearched(poiItem: PoiItem?, errorCode: Int) {
    }

    override fun onPoiSearched(poiResult: PoiResult?, errorCode: Int) {

        isLoading = false

        if (errorCode == 1000){
            //成功

            currentPage ++

            maxPage = poiResult?.pageCount?:1

            Timber.e( " ${code} ${point}-->${poiResult?.pois?.size}  ${currentPage} ${poiResult?.pageCount}");

            gasListLiveData.postValue(poiResult?.pois)
        }else{
            Timber.e(" -->error $errorCode   ${poiResult}")
        }


    }

    fun tryLoad(position:Int,count:Int){
        if (!isLoading && position == count-1){

            pendingPage = currentPage

            pendingPage++
            if (pendingPage <= maxPage){
                loadNearby(page = pendingPage)
            }
        }
    }

    fun getGasListLiveData() : LiveData<List<PoiItem>?> = gasListLiveData



}